//
//  EarningsVM.swift
//  LeTu
//
//  Created by g1 on 2024/1/4.
//

import Foundation

class EarningsVM {
    
    /// 数据分页
    private var pageNum = 1
    /// 数据长度
    private(set) var pageSize = 20
    /// 收藏数据
    var sourceArr = [EarningsRecordModel]()
    /// 余额
    private(set) var totalBalance = 0.0
    
    // MARK: - 获取收益记录
    func getIncomeRecords(isLoad: Bool, completeHandle: @escaping NetworkRequestHandle) {
        
        var pageNum = self.pageNum
        pageNum = isLoad ? pageNum + 1 : 1
        
        var param: [String : Any] = [String : Any]()
        param["page"] = pageNum
        param["pageSize"] = pageSize
        
        apiProvider.request(api: .getIncomeRecord(params: param)) { [weak self] json, jsonArr, code in
            MYLog("获取收益记录列表：", json)
                        
            var dialog = DialogMessage()

            guard let strongSelf = self, let response = Mapper<ResponseModel>().map(JSON: json) else { return completeHandle(dialog) }
            dialog.code = response.code
            dialog.message = response.msg
            guard dialog.code == 200, let dataDic = response.data as? [String: Any], let recordsDic = dataDic["data"] as? [[String: Any]] else { return completeHandle(dialog) }
            
            strongSelf.pageNum = pageNum
            let tempList = Mapper<EarningsRecordModel>().mapArray(JSONArray: recordsDic)
            if isLoad {
                strongSelf.sourceArr = strongSelf.sourceArr + tempList
            } else {
                strongSelf.sourceArr = tempList
            }
            dialog.data = tempList.count
            
            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }
        
    }
    
    // MARK: - 获取余额
    func getBalance(completeHandle: @escaping NetworkRequestHandle) {
        
        apiProvider.request(api: .getBalance) { [weak self] json, jsonArr, code in
            MYLog("获取余额：", json)
                        
            var dialog = DialogMessage()
            guard let strongSelf = self, let response = Mapper<ResponseModel>().map(JSON: json) else { return completeHandle(dialog) }
            dialog.code = response.code
            dialog.message = response.msg
            strongSelf.totalBalance = 0.0
            guard dialog.code == 200, let dataDic = response.data as? [String: Any], let balance = dataDic["balance"] as? Double else { return completeHandle(dialog) }
            strongSelf.totalBalance = balance
            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }
        
    }
    
    
}


